package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.SuppliersMapper;
import aiku.numericalcontroloa.Model.Entity.Suppliers;
import aiku.numericalcontroloa.Model.Vo.PaymentPageVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aiku.numericalcontroloa.Model.Entity.Payment;
import aiku.numericalcontroloa.Service.PaymentService;
import aiku.numericalcontroloa.Mapper.PaymentMapper;
import org.jacoco.agent.rt.internal_43f5073.core.internal.flow.IFrame;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author 马
* @description 针对表【payment】的数据库操作Service实现
* @createDate 2024-04-16 17:38:16
*/
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment>
    implements PaymentService{

    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private SuppliersMapper suppliersMapper;

    @Override
    public Result purchaseList(Integer page, Integer size,String type) {
        Page<Payment> pages = new Page<>(page,size);
        LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
        //查询这个月所有的记录
        if (type.equals("1")){
           LocalDate firstDayOfMonth = LocalDate.now().withDayOfMonth(1);
           LocalDate lastDayOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth());
           DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
           queryWrapper.between(Payment::getStorageTime, firstDayOfMonth.format(formatter), lastDayOfMonth.format(formatter));
       }


        List<Payment> payments = paymentMapper.selectPage(pages, queryWrapper).getRecords();
        Long count = paymentMapper.selectCount(queryWrapper);
        if (payments.isEmpty()){
            return Result.success();
        }
        List<String> suppIdList = payments.stream().map(Payment::getSupplierId).collect(Collectors.toList());
        List<Suppliers> suppliersList = suppliersMapper.selectList(new LambdaQueryWrapper<Suppliers>().in(Suppliers::getId, suppIdList));
        Map<String, Suppliers> suppliersMap = suppliersList.stream().collect(Collectors.toMap(Suppliers::getId, Function.identity()));
        for (Payment payment : payments) {
            Suppliers suppliers = suppliersMap.get(payment.getSupplierId());
            payment.setSupplierName(suppliers.getSuppliersName());
        }
        //根据时间排序,越新的在前面
        payments.sort(Comparator.comparing(Payment::getStorageTime).reversed());
        PaymentPageVo paymentPageVo = new PaymentPageVo();
        paymentPageVo.setPaymentList(payments);
        paymentPageVo.setTotal(count);

        return Result.success(paymentPageVo);
    }

    /**
     * 通过供应商查询采购记录
     * @param type
     * @return
     */
    @Override
    public Result purchaseReceiptsInfoList(String type) {
        LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
        if (type.equals("1")){
            LocalDate firstDayOfMonth = LocalDate.now().withDayOfMonth(1);
            LocalDate lastDayOfMonth = LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            queryWrapper.between(Payment::getStorageTime, firstDayOfMonth.format(formatter), lastDayOfMonth.format(formatter));
        }
        List<Payment> paymentList = paymentMapper.selectList(queryWrapper);
        if (paymentList.isEmpty()){
            return Result.success();
        }
        HashMap<String, Payment> payMap = new HashMap<>();
        for (Payment payment : paymentList) {
            Payment pay = payMap.get(payment.getSupplierId());
            Payment paymentOne = new Payment();
            BeanUtils.copyProperties(payment,paymentOne);
            if (pay==null){
                paymentOne.setGoodPrice(new BigDecimal("0"));
                paymentOne.setSupplierPrice(new BigDecimal("0"));
                payMap.put(paymentOne.getSupplierId(),paymentOne);
            }
            pay = payMap.get(paymentOne.getSupplierId());
            pay.setGoodPrice(pay.getGoodPrice().add(payment.getGoodPrice()));
            pay.setSupplierPrice(pay.getSupplierPrice().add(payment.getSupplierPrice()));
            System.out.println("============================================");
        }
        paymentList = payMap.values().stream().collect(Collectors.toList());

        List<String> suppIdList = paymentList.stream().map(Payment::getSupplierId).collect(Collectors.toList());
        List<Suppliers> suppliersList = suppliersMapper.selectList(new LambdaQueryWrapper<Suppliers>().in(Suppliers::getId, suppIdList));
        Map<String, Suppliers> suppliersMap = suppliersList.stream().collect(Collectors.toMap(Suppliers::getId, Function.identity()));
        for (Payment payment : paymentList) {
            Suppliers suppliers = suppliersMap.get(payment.getSupplierId());
            payment.setSupplierName(suppliers.getSuppliersName());
        }

        paymentList.sort(Comparator.comparing(Payment::getGoodPrice).reversed());
        return Result.success(paymentList);
    }

    /**
     * 通过供应商id清空供应商未结算金额
     * @param supplierId
     * @return
     */
    @Override
    public Result purchaseReceiptsInfos(String supplierId) {
        Payment payment = new Payment();
        payment.setSupplierPrice(new BigDecimal("0"));
        LambdaUpdateWrapper<Payment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Payment::getSupplierId,supplierId);
        int i = paymentMapper.update(payment, updateWrapper);
        return i>0 ? Result.success("结算成功") : Result.error(201,"结算失败");
    }
}




